package com.hy;

import java.util.Arrays;

/**
 * Created With IntelliJ IDEA.
 * Descriptions:最接近的三数之和
 *
 * 给你一个长度为 n 的整数数组 nums 和 一个目标值 target。请你从 nums 中选出三个整数，使它们的和与 target 最接近。
 *
 * 返回这三个数的和。
 *
 * 假定每组输入只存在恰好一个解。
 * User:Mr.Du
 * Date:2023/11/11
 * Time:21:48
 */
public class ThreeSumClosest {

    public int threeSumClosest(int[] nums, int target) {
        int len = nums.length;
        Arrays.sort(nums);
        int res = 1000000;
        int tmp = 1000000;
        for(int i = 0;i < len - 2;i++){
            if(i > 0 && nums[i] == nums[i-1]) continue;
            int j = i + 1;
            int k = len - 1;
            int s = 0;
            while(j < k){
                s = nums[i] + nums[j] + nums[k];
                if(tmp > Math.abs(target - s)){
                    tmp = Math.abs(target - s);
                    res = s;
                }
                if (s > target){
                    k--;
                }else if(s < target){
                    j++;
                }else{
                    return s;
                }
            }


        }
        return res;
    }

    public static void main(String[] args) {
        int[] nums = {2, 3, 8, 9, 10};
        ThreeSumClosest threeSumClosest = new ThreeSumClosest();
        int res = threeSumClosest.threeSumClosest(nums, 16);
        System.out.println(res);
    }
}
